package random

import (
	"math/rand"
	"time"
)

//sample one
func Sample(m map[int32]int32) int32 {
	var toDelete []int32
	for k, v := range m {
		if v == 0 {
			toDelete = append(toDelete, k)
		}
	}
	for _, eachDeleting := range toDelete {
		delete(m, eachDeleting)
	}
	if len(m) > 0 {
		new := time.Now().UnixNano()
		rand.Seed(new)
		var sum int32 = 0
		for _, v := range m {
			sum += v
		}
		var p = rand.Int31n(sum)
		for i, v := range m {
			p -= v
			if p <= 0 {
				return i
			}
		}
	}
	return 0
}

//sample n without replace
func SampleN(m map[int32]int32, n int) []int32 {
	var toDelete []int32
	for k, v := range m {
		if v == 0 {
			toDelete = append(toDelete, k)
		}
	}
	for _, eachDeleting := range toDelete {
		delete(m, eachDeleting)
	}

	if len(m) > 0 {
		rand.Seed(time.Now().UnixNano())
		mCopy := make(map[int32]int32)
		for mk, mv := range m {
			mCopy[mk] = mv
		}
		var samples []int32
		for i := 0; i < n && len(mCopy) > 0; i++ {
			selectedKey := Sample(mCopy)
			samples = append(samples, int32(selectedKey))
			delete(mCopy, selectedKey)
		}
		return samples
	}
	return nil
}
